﻿
var chat;
$(function () {
    try {
        // Declare a proxy to reference the hub.
        chat = $.connection.chatHub;
        $.connection.hub.start().done(function () {
            chat.server.loggedIn().done(function (result) {
                if (result == true) {
                    chat.server.getUserId().done(function (userId) {
                        $.connection.hub.id = userId;
                    });
                    chat.server.updateUnreadMessages();

                }
                else {
                    $.connection.hub.stop();
                }
            });


        });

    }
    catch (err) {
        alert("error caught");
        alert(err.message.toString());
    }
    //chat.client.loadSenders = function (conversationList) {
    //    alert("hej1");
    //    //var index = 2;
    //    //for (var convesation in listOfConversations) {
    //    //    alert("hej" + index);
    //    //    index++;
    //    //}
    //    alert(listOfConversations.length);
    //    alert(listOfConversations);
    //};
    //chat.server.listTest().done(function (test) {
    //    alert("hej1");
    //});

    chat.client.test2 = function (test) {
        alert("hej1");
        for (var i = 0; i < test.length; i++) {
            alert(test[i]);
        }
    };

    chat.client.updateUnreadMessages = function (amountOfMessages) {
        $(messagesA).html("Beskeder(" + amountOfMessages + ")");
    };

    chat.client.test = function () {
        alert("hej1");
    };



});



function openMessageCenter() {
    var messageCenter = document.createElement('div');
    messageCenter.id = "messagecenter";
    messageCenter.style.backgroundColor = "white";
    messageCenter.style.height = "600px";
    messageCenter.style.width = "900px";
    messageCenter.style.top = "130px";
    messageCenter.style.left = "0";
    messageCenter.style.right = "0";
    messageCenter.style.marginRight = "auto";
    messageCenter.style.marginLeft = "auto";
    messageCenter.style.zIndex = "10";
    messageCenter.style.border = "solid 1px";




    var innerMessageCenter =
        "<div class='navbar-inner' style='width: 99.8%; text-align: center; padding-left: 0px; padding-right: 0px;'>" +
            "<p ID='mc_beskeder-top' style=''>Samtaler</p>" +
            "<a href='#' onclick='closeMessageCenter()'><img src='images/close-button.png' style='height: 40px; width:40px; position:absolute; top:5px; right:5px;' /></a>" +
        "</div>" +
        "<div id='leftside' class='mc_leftside' style='width:33%; height:548px; background-color:white;'>" +
            "<ul id='listOfSenders' style='list-style:none; margin-left:0px;' >" +
            "</ul>" +
        "</div>" +
        "<div id='rightSide' class='mc_rightSide'>" +
                "<ul id='listOfMessages' style='list-style:none;' >" +
                "</ul>" +
        "</div>" +
        "<div id='textbox_outer' class='mc_textbox_outer'>" +
            "<div id='textbox_inner' class='mc_textbox'>" +
                "<textarea id='mc_textToBeSend' style='width:568px; height:90px; margin-top:8px;'></textarea>" +
            "</div>" +
            "<button type='button' class='btn btn-success'>Send</button>"+
        "</div>";


    messageCenter.innerHTML = innerMessageCenter;
    document.body.appendChild(messageCenter);
    $('#leftside').perfectScrollbar();
    $('#rightSide').perfectScrollbar();

    chat.server.getSenders().done(function (results) {
        insertListOfSenders(results);
    });


    textbox_inner.addEventListener('keypress', checkKeyPress, false);

    $('#textbox_inner').on('keyup', 'textarea', function (e) {
        if (this.scrollHeight > 259) {
            if (this.scrollHeight > this.offsetHeight) {

            }
            else {
                if (e.which == 8) {
                    $(this).css('height', 'auto');
                    $(this).height(this.scrollHeight);
                    var newHeightDifference = $(this).height() - 59;
                    $(rightSide).height(400 - newHeightDifference);
                    $(textbox_outer).height(146 + newHeightDifference);

                }
            }
        }
        else {
            $(this).css('overflow-y', 'hidden');
            $(this).css('height', 'auto');
            $(this).height(this.scrollHeight);
            if ($(this).height() > 59) {
                var newHeightDifference = $(this).height() - 59;
                $(rightSide).height(400 - newHeightDifference);
                $(textbox_outer).height(146 + newHeightDifference);
                $("#rightSide").animate({ scrollTop: $("#rightSide")[0].scrollHeight }, 350);

            }
            else {
                $(rightSide).height(400);
                $(textbox_outer).height(146);
            }
        }
    });
    $('#textbox_inner').find('textarea').keyup();
    $('#textbox_inner').find('textarea').keydown();
}

function closeMessageCenter() {
    $('#messagecenter').remove();
}

function insertListOfSenders(results) {
    var newListOfSenders = document.createElement("ul");
    newListOfSenders.id = "newListOfSenders";
    newListOfSenders.setAttribute("style", "display:none;");
    $('#leftside').append(newListOfSenders);
    for (var i = 0; i < results.length; i++) {
        var newListItem = document.createElement("li");
        var srcOfImage;
        if (ImageExist("/Dateiaften1/images/ProfilePictures/" + results[i].username + ".png"))
            srcOfImage = ("/Dateiaften1/images/ProfilePictures/" + results[i].username + ".png");
        else
            srcOfImage = "/Dateiaften1/images/ProfilePictures/default.png";


        newListItem.innerHTML =
            "<a href='#' onclick='loadMessages(" + results[i].conversationId + ")' contenteditable='false' >" +
                "<div class='mc_listOfSendersItem_outer'>" +
                    "<div class='mc_listOfSendersItem'>" +
                        "<img id='" + results[i].conversationId + results[i].username + "ProfilePic' class='mc_profilePic' src='" + srcOfImage + "' />" +
                        "<p class ='mc_listOfSendersItem_username' >" + results[i].username + "</p><p class='mc_listOfSendersItem_date' > " + calcDate(results[i].timeOfLastMessage) + " </p>" +
                        "<p class='mc_listOfSendersItem_lastmessage' >" + results[i].lastMessageUsername + ": " + results[i].lastMessage + "</p>" +
                    "</div>" +
                "</div>" +
            "</a>" +
            "<hr class='featurette-divider' style='margin:0 auto; width:90%;' />";

        newListItem.setAttribute("data-id", results[i].username + results[i].conversationId);
        $("#newListOfSenders").append(newListItem);
    }
    try {
        if ($("#listOfSenders li").length == 0) {
            $("#newListOfSenders").children().appendTo("#listOfSenders");
            $('#newListOfSenders').remove();
            $("#listOfSenders li").first().find("a").click();
        }
        else {
            $('#listOfSenders').quicksand($('#newListOfSenders li'),
                {
                },
                function () { // callback function
                    $('#newListOfSenders').remove();
                }
                );
        }
    }
    catch (err) {
        alert(err.message);
    }
}

function checkKeyPress(e) {
    var charCode = e.charCode;
    if (charCode == 13 && !e.shiftKey) {
        try {
            e.preventDefault();
        } catch (ee) {
            alert(ee.message);

        }
    }
}

function ImageExist(url) {
    var img = new Image();
    img.src = url;
    return img.height != 0;
}

function loadMessages(conversaionId) {
    alert("hej1");
    chat.server.getMessages(conversaionId).done(function (resultList) {
        alert("hej2");
        $("#listOfMessages").empty();
        for (var i = 0; i < resultList.length; i++) {
            var newListItem = document.createElement("li");
            var srcOfImage;
            if (ImageExist("/Dateiaften1/images/ProfilePictures/" + resultList[i].sentByUser + ".png"))
                srcOfImage = ("/Dateiaften1/images/ProfilePictures/" + resultList[i].sentByUser + ".png");
            else
                srcOfImage = "/Dateiaften1/images/ProfilePictures/default.png";

            var text = resultList[i].messageSent.toString();
            text = text.replace(/\r?\n/g, '<br />');

            newListItem.innerHTML =
                "<div class='mc_messageArea_main' >" +
                    "<div class='mc_messageArea_leftside'>" +
                        "<img id='" + resultList[i].messageId + resultList[i].sentByUser + "ProfilePic' class='mc_profilePic' src='" + srcOfImage + "' />" +
                    "</div >" +
                    "<div class='mc_messageArea_center' >" +
                        "<p class='mc_messageArea_center_username'>" +
                            resultList[i].sentByUser + ": " +
                        "</p>" +
                        "<p class='mc_messageArea_center_message'>" +
                            text +
                        "</p>" +
                    "</div >" +
                    "<div class='mc_messageArea_rightside' >" +
                    "<p class='mc_messageArea_rightside_date'>" +
                        calcDateWithTime(resultList[i].timeOfMessageSent) +
                    "</p>" +
                    "</div >" +
                "</div>";

            newListItem.setAttribute("data-id", resultList[i].sentByUser + resultList[i].messageId);
            $("#listOfMessages").append(newListItem);
        }
        $("#rightSide").animate({ scrollTop: $("#rightSide")[0].scrollHeight }, 750);

        chat.server.updateMessages(conversaionId);

        chat.server.getOtherUserByConversation(conversaionId).done(function (user)
        {
            $("#newUserTagDiv").remove();
            var srcOfImage;
            if (ImageExist("/Dateiaften1/images/ProfilePictures/" + user[0].username + ".png"))
                srcOfImage = ("/Dateiaften1/images/ProfilePictures/" + user[0].username + ".png");
            else
                srcOfImage = "/Dateiaften1/images/ProfilePictures/default.png";

            var newUserTagDiv = document.createElement("div");
            newUserTagDiv.setAttribute("style", "width:50%; height:45px; float:left;")
            newUserTagDiv.id = "newUserTagDiv";
            newUserTagDiv.innerHTML =
            "<img src='" + srcOfImage + "' style='heigh:45px; width:45px; float:left; margin-left:9.250px; margin-top:-3px;'>" +
            "</img>" +
            "<div style='height:20px; width:100%;'>"+
                "<p style='float:left; margin-left:13px; margin-bottom:0px; font-size: 16px; color: #333; font-weight: bold; height:16px; border-bottom: solid 1px;'>" +
                    user[0].username+
                "</p>" +
            "</div>" +
            "<div style='height:13px; width:100%; color: gray; font-size: 11px; '>" +
                "<p style='float:left; height:13px; margin-left:13px; margin-bottom:0px; margin-top:-4px;'>" +
                    "Bor i: "+user[0].city+
                "</p>"+
            "</div>"+
            "<div style='height:13px; width:100%; color: gray; font-size: 11px; '>" +
                "<p style='float:left; height:13px; margin-left:13px; margin-bottom:0px; margin-top:-7px;'>" +
                    "Alder: " + user[0].age + " år"+
                "</p>" +
            "</div>";

            $("#textbox_outer").append(newUserTagDiv);


            //alert(user[0].username);
        });
    });
}

function test() {
    alert("hej1");
}

function getMonthName(monthNumber) {

    var monthNames = new Array('Januar', 'Febuar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'August', 'september', 'Oktober', 'November', 'December');
    return monthNames[monthNumber];
}

function newMessage(conversationId) {

}

function calcDate(lastMessage) {
    var currentdate = new Date();
    var timeOfLastMessage = new Date(lastMessage.toString());
    if ((timeOfLastMessage.getDate() == currentdate.getDate()) && (timeOfLastMessage.getMonth() == currentdate.getMonth())) {
        var s = "";
        s += timeOfLastMessage.getHours();
        s += ":";
        s += timeOfLastMessage.getMinutes();
        return s;
    }
    else {
        var s = "";
        s += timeOfLastMessage.getDate();
        s += ". ";
        s += getMonthName(timeOfLastMessage.getMonth());
        return s;
    }
}

function calcDateWithTime(lastMessage) {
    var currentdate = new Date();
    var timeOfLastMessage = new Date(lastMessage.toString());
    if ((timeOfLastMessage.getDate() == currentdate.getDate()) && (timeOfLastMessage.getMonth() == currentdate.getMonth())) {
        var s = "";
        s += timeOfLastMessage.getHours;
        s += ":";
        s += timeOfLastMessage.getMinutes;
        return s;
    }
    else {
        var s = "";
        s += timeOfLastMessage.getDate();
        s += ". ";
        s += getMonthName(timeOfLastMessage.getMonth());
        s += " ";
        s += timeOfLastMessage.getHours();
        s += ":";
        if (timeOfLastMessage.getMinutes().toString().length < 2)
            s += "0" + timeOfLastMessage.getMinutes();
        else
            s += timeOfLastMessage.getMinutes();
        return s;
    }
}



